import router from '@/router'
// 引入进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
// 去除进度条小球
nprogress.configure({
    showSpinner: false
})

import setting from '@/setting'

// 从pinia里获取token判断用户是否登录
import useUserStore from '@/store/modules/user'
import pinia from '@/store'
let userStore = useUserStore(pinia);

// 路由守卫： 任意路由访问都会触发
// 前置路由
router.beforeEach(async (to:any, from:any, next:any) => {
    nprogress.start()

    // 页签标题
    document.title = `${setting.title} - ${to.meta.title}`

    let token = userStore.token
    let username = userStore.username
    if(token){
        if(to.path === '/login'){
            next('/home')
        }else{
            if(username){
                next()
            }else{
                try {
                    await userStore.userInfo();
                    next()
                }catch(error) {
                    // token过期：获取不到用户信息->退出登录清空用户信息
                    await userStore.userLogout()
                    // 退出登录后，再回来还回到当初的地方
                    next({path: '/login',query:{redirect:to.path}})
                }
            }
        }
    }else{
        if(to.path === '/login'){
            next()
        }else{
            next({path: '/login',query:{redirect:to.path}})
        }
    }
})
// 后置路由
router.afterEach((to:any, from:any) => {
    nprogress.done()
})